package com.kalman.webx;

import static com.google.common.base.Strings.isNullOrEmpty;

import java.net.URLEncoder;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.citrus.turbine.TurbineRunData;
import com.alibaba.citrus.turbine.util.TurbineUtil;
import com.alibaba.citrus.util.i18n.LocaleUtil;


public class LoginHelper {

	/**
	 * URL参数最长为 1000。
	 */
	private final static int MAX_URL_GET_LENTH = 1000;

	@SuppressWarnings("rawtypes")
	private static String getPostParms(TurbineRunData rundata) {
		String query = null;
		final StringBuilder sb = new StringBuilder();
		for (Iterator iter = rundata.getParameters().keySet().iterator(); iter.hasNext();) {
			String parmName = (String) iter.next();
			String parmValue = rundata.getParameters().getString(parmName);
			try {
				if (!isNullOrEmpty(parmValue)&& parmValue.length() < MAX_URL_GET_LENTH / 10) {
					sb.append(parmName).append("=").append(URLEncoder.encode(parmValue, LocaleUtil.getContext().getCharset().toString())).append("&");
				}
			} catch (Exception e) {
				// ignore
			}
		}
		if (sb.length() > 0) {
			int len = sb.length();
			query = sb.substring(0, len - 1);
		}
		if (sb.length() > MAX_URL_GET_LENTH) {
			query = sb.substring(0, MAX_URL_GET_LENTH);
		}
		return query;
	}
	/**
	 * 获取请求的参数，包含post的数据
	 * @param request
	 * @return
	 */
	public static String getRequestParams(HttpServletRequest request){
		TurbineRunData rundata = TurbineUtil.getTurbineRunData(request);
		return getPostParms(rundata);
	}
	
	public static String getRedirectUrl (HttpServletRequest request){
		String queryString = getRequestParams(request);
		if (queryString != null){
			return request.getRequestURL().toString() + "?" + queryString;
		}
		return request.getRequestURL().toString();
	}
}
